package auth

import (
	"center-data-platform/app/auth/api/internal/svc"
	"center-data-platform/app/auth/api/internal/types"
	"center-data-platform/app/auth/api/model"
	"center-data-platform/utils/helper"
	"context"
	"errors"
	"github.com/golang-jwt/jwt/v4"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type AuthLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

type Claims struct {
	UserId int    `json:"user_id"`
	Email  string `json:"email"`
	jwt.RegisteredClaims
}

func NewAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AuthLogic {
	return &AuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AuthLogic) Auth(req *types.Request) (resp *types.Response, err error) {
	res, err := l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
	if err != nil {
		return nil, errors.New("用户邮箱不正确")
	}
	if !helper.Compared(res.Password, req.Password+res.Salt) {
		return nil, errors.New("用户密码不正确")
	}

	token, err := l.GenerateToken(res)
	if err != nil {
		return nil, err
	}
	resp = &types.Response{
		Token: token,
	}
	return resp, nil
}

func (l *AuthLogic) GenerateToken(users *model.Users) (string, error) {
	claim := Claims{
		UserId: int(users.Id),
		Email:  users.Email,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(l.svcCtx.Config.Auth.AccessExpire))),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenStr, err := token.SignedString([]byte(l.svcCtx.Config.Auth.AccessSecret))

	return tokenStr, err
}
